#!/bin/bash

echo "🚀 启动PokerMind TCP服务器..."
echo "=========================================="
echo ""

# 检查端口8889是否被占用
echo "🔍 检查端口8889占用状态..."
PORT_PID=$(lsof -ti :8889)

if [ ! -z "$PORT_PID" ]; then
    echo "⚠️  端口8889被进程占用 (PID: $PORT_PID)"
    echo "🛑 正在停止占用进程..."
    
    # 尝试优雅关闭
    kill -TERM $PORT_PID 2>/dev/null
    sleep 2
    
    # 检查进程是否还在运行
    if kill -0 $PORT_PID 2>/dev/null; then
        echo "🔨 强制停止进程..."
        kill -9 $PORT_PID 2>/dev/null
    fi
    
    # 等待端口释放
    sleep 1
    
    # 再次检查
    NEW_PID=$(lsof -ti :8889)
    if [ ! -z "$NEW_PID" ]; then
        echo "❌ 无法释放端口8889，请手动处理"
        exit 1
    fi
    
    echo "✅ 端口8889已释放"
else
    echo "✅ 端口8889未被占用"
fi

echo ""
echo "📋 配置信息:"
echo "   🌐 监听地址: 127.0.0.1:8889"
echo "   📡 协议: JSON over Binary Frame"
echo "   🔧 模式: 生产模式"
echo ""
echo "🛑 停止服务器请按 Ctrl+C"
echo ""

# 确定脚本所在目录（TCP模块目录）
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
echo "📂 TCP模块目录: $SCRIPT_DIR"
echo ""

# 切换到项目根目录，编译TCP模块及其依赖
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
echo "📂 项目根目录: $PROJECT_ROOT"
echo ""

cd "$PROJECT_ROOT"
echo "🔄 清理缓存、编译并安装到本地仓库（确保exec:java使用最新代码）..."
    mvn clean install -pl pokermind-serv-dse-tcp -am -DskipTests -Dmaven.test.skip=true -q
echo "✅ 编译并安装完成"
echo ""

echo "🚀 启动服务器..."
mvn exec:java -pl pokermind-serv-dse-tcp -Dexec.mainClass="com.pokermind.dse.tcp.DseTcpApplication" -Dspring.profiles.active=dev
